﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using Sunboxsoft.Common;
using DevExpress.XtraEditors;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using LocalService = Sunboxsoft.ASMS.Client.Domain.LocalService;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Edit
{
    public partial class UpdateBookingAutoMobileView : UserControl, IView
    {
        WebRef.VCustomer _vCustomer = null;
        WebRef.VAutomobile _vAutomobile = null;
        Promise _promise = new Promise();
        public UpdateBookingAutoMobileView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(ctlEditCarOwnerName, "车主姓名", true));
            ValidationManager.Register(this, new Common.Validations.TextEditTelephoneValidation(ctlEditCarOwnerTel, true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(ctlEditCarLPN, "车牌号", false));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(ctlEditCarVIN, "车架号", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(ctlEditEIN, "发动机编号", true));
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(ctlSearchLookUpCarBrand, "汽车品牌"));
        }
        public UpdateBookingAutoMobileView(WebRef.VCustomer model, WebRef.VAutomobile vAutomobile)
            : this()
        {
            this._vCustomer = model;
            this._vAutomobile = vAutomobile;
        }
        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("save", Resources.isOK, "保存", OnBtnSave_Click))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", OnBtnCancel_Click));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise
            .Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(this.ctlSearchLookUpCarBrand,
                   _promise,
                   Domain.Constant.MasterDataCodes.AutomobileBrand,
                   null,
                   null,
                   true,
                   true);
            })
             .Then(() =>
             {
                 SearchLookUpEditUtil.BindEMasterDataItem(this.ctlSearchLookUpInsuranceCompany,
               _promise,
               Domain.Constant.MasterDataCodes.InsuranceCompany,
               null,
               null,
               true,
               true);
             }).Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    GetAutoMobile();
                    _promise.Resolve();
                }));
            })
            .Run();
        }
        public void Resume(ViewResumeArgs args)
        {

        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("修改车辆信息");
        }
        #endregion

        #region Method
        /// <summary>
        /// 获取待修改车辆信息
        /// </summary>
        private void GetAutoMobile()
        {
            if (_vCustomer != null)
            {
                this.txtCustomerID.Text = _vCustomer.Number;
                this.txtCustomerName.Text = _vCustomer.Name;
                this.txtCustomerPhone.Text = _vCustomer.Telephone;
            }
            if (_vAutomobile != null)
            {
                this.ctlEditCarOwnerName.Text = _vAutomobile.Owner;
                this.ctlEditCarOwnerTel.Text = _vAutomobile.OwnerTelephone;
                this.ctlEditCarLPN.Text = _vAutomobile.LPN;
                this.ctlEditCarVIN.Text = _vAutomobile.VIN;
                this.ctlEditEIN.Text = _vAutomobile.EIN;
                this.ctlEditEngineType.Text = _vAutomobile.EngineType;
                ctlSearchLookUpCarBrand.SelectEMasterDataItem(_vAutomobile.Brand);
                this.ctlEditBoughtDate.EditValue = _vAutomobile.BoughtDate;
                ctlSearchLookUpInsuranceCompany.SelectEMasterDataItem(_vAutomobile.InsuranceCompany);
                this.ctlEditInsuranceExpire.Text = _vAutomobile.InsuranceExpirationDate.ToString();
                this.ctlEditInsuranceNum.Text = _vAutomobile.InsuranceNumber;
                this.ctlEditNextTime.Text = _vAutomobile.NextAnnualSurveyDate.ToString();
            }
        }
        /// <summary>
        /// 添加车辆信息
        /// </summary>
        private void UpdateAutomobile()
        {
            WebRef.EAutomobile modelMobile = new WebRef.EAutomobile();
            modelMobile.Id = _vAutomobile.Id;
            if (_vCustomer != null)
            {
                modelMobile.CustomerId = _vCustomer.Id;
            }
            modelMobile.Owner = this.ctlEditCarOwnerName.Text.Trim();
            modelMobile.OwnerTelephone = this.ctlEditCarOwnerTel.Text.Trim();
            modelMobile.LPN = this.ctlEditCarLPN.Text.Trim();
            modelMobile.VIN = this.ctlEditCarVIN.Text.Trim();
            modelMobile.EIN = this.ctlEditEIN.Text.Trim();
            modelMobile.EngineType = this.ctlEditEngineType.Text.Trim();
            modelMobile.Brand = GetSelectedMasterDataItem(this.ctlSearchLookUpCarBrand);
            modelMobile.Maker = GetSelectedMasterDataItem(this.ctlSearchLookUpCarMarker);
            modelMobile.Series = GetSelectedMasterDataItem(this.ctlSearchLookUpSeries);
            modelMobile.Model = GetSelectedMasterDataItem(this.ctlSearchLookUpModule);
            if (this.ctlEditBoughtDate.EditValue != null)
            {
                modelMobile.BoughtDate = Convert.ToDateTime(this.ctlEditBoughtDate.EditValue);
            }
            modelMobile.InsuranceCompany = GetSelectedMasterDataItem(this.ctlSearchLookUpInsuranceCompany);
            if (!string.IsNullOrEmpty(this.ctlEditInsuranceExpire.Text.Trim()))
            {
                modelMobile.InsuranceExpirationDate = Convert.ToDateTime(this.ctlEditInsuranceExpire.Text.Trim());
            }
            modelMobile.InsuranceNumber = this.ctlEditInsuranceNum.Text.Trim();
            if (!string.IsNullOrEmpty(this.ctlEditNextTime.Text.Trim()))
            {
                modelMobile.NextAnnualSurveyDate = Convert.ToDateTime(this.ctlEditNextTime.Text.Trim());
            }
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.UpdateService().UpdateAutomobile(_vAutomobile.Id, modelMobile);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                    }
                    this.HideMask();
                }));
            });
        }
        /// <summary>
        /// 获取选择的主数据
        /// </summary>
        /// <returns></returns>
        private string GetSelectedMasterDataItem(SearchLookUpEdit searchLookUpEdit)
        {
            WebRef.EMasterDataItem item = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(searchLookUpEdit);
            if (item == null)
            {
                return null;
            }
            else
            {
                return item.Code;
            }
        }
        #endregion

        #region Action
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnSave_Click(object sender, object e)
        {
            string message = null;
            if (ValidationManager.Validate(this, out message))
            {
                UpdateAutomobile();
            }
            else
            {
                UIContext.Current.ViewManager.ShowError(message);
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnCancel_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }
        /// <summary>
        /// 根据品牌获取厂商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpCarBrand_EditValueChanged(object sender, EventArgs e)
        {
            Promise promise = new Promise();
            promise.Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(this.ctlSearchLookUpCarMarker,
                    promise,
                    Domain.Constant.MasterDataCodes.AutomobileMaker,
                    GetSelectedMasterDataItem(this.ctlSearchLookUpCarBrand),
                    null, false, true);
            })
            .Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    ctlSearchLookUpCarMarker.SelectEMasterDataItem(_vAutomobile.Maker);
                    promise.Resolve();
                }));
            })
            .Run();
        }
        /// <summary>
        /// 根据厂商获取车系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpCarMarker_EditValueChanged(object sender, EventArgs e)
        {
            Promise promise = new Promise();
            promise.Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(this.ctlSearchLookUpSeries,
                    promise,
                    Domain.Constant.MasterDataCodes.AutomobileSeries,
                    GetSelectedMasterDataItem(this.ctlSearchLookUpCarMarker),
                     null, false, true);
            })
            .Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    ctlSearchLookUpSeries.SelectEMasterDataItem(_vAutomobile.Series);
                    promise.Resolve();
                }));
            })
            .Run();
        }
        /// <summary>
        /// 根据车系获取车型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchLookUpSeries_EditValueChanged(object sender, EventArgs e)
        {
            Promise promise = new Promise();
            promise.Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(this.ctlSearchLookUpModule,
                    promise,
                    Domain.Constant.MasterDataCodes.AutomobileModel,
                    GetSelectedMasterDataItem(this.ctlSearchLookUpSeries),
                     null, false, true);
            })
            .Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    ctlSearchLookUpModule.SelectEMasterDataItem(_vAutomobile.Model);
                    promise.Resolve();
                }));
            })
            .Run();
        }
        #endregion
    }
}
